package task

import (
	"encoding/json"
	"github.com/name5566/leaf/gate"
	"github.com/name5566/leaf/log"
	"github.com/name5566/leaf/recordfile"
	db2 "server/db"
	"server/game/task/db"
	"server/game/task/tmp"
	"server/msg/jsonData"
	"server/util"
)

var taskTable = "task"

func JieShouTask(args []interface{}) {
	m := args[0].(*jsonData.MsgCreateTaskInfoReq)
	// 消息的发送者
	a := args[1].(gate.Agent)

	// 输出收到的消息的内容
	_, err := checkTaskExit(m.TaskId)
	if err == nil {
		a.WriteMsg(&jsonData.MsgCreatePlayerRes{
			Ret: jsonData.ErrCode(2),
		})
		return
	}
	data := db.TaskInfoData{
		TaskId:     util.CreateUUid(),
		TaskTmpId:  m.TaskId,
		TaskVar:    initTaskVar(),
		UserId:     m.UserId,
		TaskStatus: db.TaskState_TaskState_UnFinish,
	}
	err = db2.Db.Insert(taskTable, data)
	if err != nil {
		a.WriteMsg(&jsonData.MsgCreatePlayerRes{
			Ret: jsonData.ErrCode(0),
		})
		return
	}

	// 给发送者回应一个 Hello 消息
	a.WriteMsg(&jsonData.MsgCreatePlayerRes{
		Ret: jsonData.ErrCode(0),
	})
}

func WanChengRenWu(args []interface{}) {
	m := args[0].(*jsonData.MsgUpdateTaskStateReq)
	// 消息的发送者
	a := args[1].(gate.Agent)

	// 输出收到的消息的内容
	log.Debug("hello %d", m.TaskId)
	taskInfo, err := checkTaskExit(m.TaskId)
	if err != nil {
		a.WriteMsg(&jsonData.MsgCreatePlayerRes{
			Ret: jsonData.ErrCode(2),
		})
		return
	}
	if taskInfo.TaskStatus != db.TaskState_TaskState_SholdBeFinish {
		log.Error("任务还没s")
		return
	}
	taskInfo.TaskStatus = db.TaskState_TaskState_Finish
	err = db2.Db.Update(taskTable, map[string]interface{}{"task_id": m.TaskId}, map[string]interface{}{"task_status": db.TaskState_TaskState_Finish})
	if err != nil {
		log.Error("log is " + err.Error())
		return
	}
	// 给发送者回应一个 Hello 消息
	a.WriteMsg(&jsonData.MsgRes{
		Ret: jsonData.ErrCode(0),
	})
}
func UpdateTaskVar(userId string, action int, value int, gate gate.Agent) {
	var TaskLists []db.TaskInfoData
	err := db2.Db.Find(taskTable, map[string]interface{}{"user_id": userId}, &TaskLists)
	if err != nil {
		return
	}

	for _, taskInfo := range TaskLists {
		taskVar := make(map[int]int)
		json.Unmarshal([]byte(taskInfo.TaskVar), &taskVar)
		newtaskVar, check := checkTaskCondition(taskInfo.TaskTmpId, taskVar, action, value)
		if check == true {
			taskInfo.TaskStatus = db.TaskState_TaskState_SholdBeFinish
			//gate.WriteMsg(&msg.MsgUpdateTaskStateRes{
			//	Ret: 1,
			//	T
			//		})
		}
		taskByVar, _ := json.Marshal(newtaskVar)
		taskInfo.TaskVar = string(taskByVar)
		db2.Db.Update(taskTable,
			map[string]interface{}{"task_id": taskInfo.TaskId},
			map[string]interface{}{"task_var": taskInfo.TaskVar})

	}
}

func GetTaskLis(args []interface{}) {
	m := args[0].(*jsonData.MsgTaskListReq)
	// 消息的发送者
	a := args[1].(gate.Agent)
	var TaskLists []*db.TaskInfoData
	err := db2.Db.Find(taskTable, map[string]interface{}{"user_id": m.UserId}, &TaskLists)
	if err != nil {
		return
	}
	var TaskInfoList []jsonData.TaskInfo // 定义最终结果存储的列表

	for _, taskInfoTmp := range TaskLists {
		// 将 Task 转换为 msg.TaskInfo
		taskInfo := jsonData.TaskInfo{
			TaskId:    taskInfoTmp.TaskTmpId,
			UserId:    taskInfoTmp.UserId,
			TaskVar:   taskInfoTmp.TaskVar,
			TaskState: taskInfoTmp.TaskStatus,
		}

		// 将转换后的对象添加到 TaskInfoList
		TaskInfoList = append(TaskInfoList, taskInfo)
	}
	a.WriteMsg(&jsonData.MsgRes{Ret: jsonData.ErrCode(0),
		TaskList: TaskInfoList})
}
func checkTaskCondition(taskId int64, taskVar map[int]int, action int, value int) (map[int]int, bool) {
	var check bool = false
	taskTmp, err := recordfile.New(tmp.TaskTmp{})
	if err != nil {
		log.Error(err.Error())
		return taskVar, false
	}
	checkCondition := taskTmp.Index(taskId).(*tmp.TaskTmp)
	for taskAction, taskValue := range taskVar {
		if taskAction == action {
			value = taskValue + value
			taskVar[taskAction] = value
			if checkCondition.Condition == action {
				//此处判断任务的条件
				if checkCondition.Param[action] <= taskValue {
					check = true
				} else {
					check = false
				}
			}
		}
	}

	return taskVar, check
}
func checkTaskExit(taskId int64) (db.TaskInfoData, error) {
	var result db.TaskInfoData
	err := db2.Db.FindOne(taskTable, map[string]interface{}{"id": taskId}, &result)
	if err == nil {
		return result, nil
	}
	return result, err
}
func initTaskVar() string {
	taskVar := make(map[int]int)
	data, err := json.Marshal(taskVar)
	if err != nil {
		log.Error("")
	}
	return string(data)
}
